package com.useeinfo.testgit;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import static android.content.ContentValues.TAG;

/**
 * Created by lvyongxu on 2016-01-22 13:40.
 */
public class MyUtils {

    /**
     * 显示键盘
     *
     * @param editText 要获取光标并显示键盘的控件
     */
    public static void showKeyboard(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();

        InputMethodManager inputManager = (InputMethodManager) editText.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(editText, 0);
    }

    /**
     * 是否需要手动处理权限问题（手机系统版本是否高于等于 Marshmallow 23 版本）
     *
     * @return true 需要； false：不需要
     */
    public static boolean needManualAskPermission() {
        return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M);
    }

    /**
     * 获取软件版本号
     *
     * @return 当前应用的版本号
     */
    public static String getVersionName(Context context) {
        String version;
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
//            version1 = info.versionCode;//build
            version = info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            version = "N/A";
        }
        return version;
    }

    /**
     * 将用户当前所用设备信息保存至本地
     *
     * @param activity
     */
    public static void saveUserAgent(Activity activity) {
        // 将设备信息保存至本地，并在每个网络请求头里添加此字段
        try {
            String model = Build.MODEL;
            String androidVersion = Build.VERSION.RELEASE;
            WindowManager windowManager = activity.getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            int screenWidth = display.getWidth();
            int screenHeight = display.getHeight();
            String scale = screenWidth + "*" + screenHeight;
            PackageManager manager = activity.getPackageManager();
            PackageInfo info = null;
            try {
                info = manager.getPackageInfo(activity.getPackageName(), 0);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            String appVersion = info.versionName;

            String userAgent = String.format(BuildConfig.APPLICATION_ID + "/%s(android;%s;%s;%s)",
                    appVersion, androidVersion, java.net.URLDecoder.decode(model), scale);
            Log.e(TAG, "userAgent=" + userAgent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
